let assetBaseUrl = ''
try {
  const config = require('../config.js')
  assetBaseUrl = config && (config.assetBaseUrl || config.ASSET_BASE_URL) || ''
} catch (error) {
  assetBaseUrl = ''
}

function hasProtocol(url) {
  return /^(https?:)?\/\//i.test(url) || url.indexOf('wxfile://') === 0 || url.indexOf('data:') === 0
}

function ensureAbsoluteUrl(url, options = {}) {
  const base = typeof options.base === 'string' ? options.base : assetBaseUrl
  if (!url) {
    return url
  }
  let value = url
  if (typeof value !== 'string') {
    value = String(value)
  }
  value = value.trim()
  if (!value) {
    return value
  }
  if (hasProtocol(value)) {
    return value
  }
  if (!base) {
    return value
  }
  let normalizedBase = base.trim()
  if (!normalizedBase) {
    return value
  }
  if (normalizedBase.lastIndexOf('/') === normalizedBase.length - 1) {
    normalizedBase = normalizedBase.substring(0, normalizedBase.length - 1)
  }
  if (value.charAt(0) !== '/') {
    value = '/' + value
  }
  return normalizedBase + value
}

module.exports = {
  ensureAbsoluteUrl,
  getAssetBaseUrl() {
    return assetBaseUrl
  }
}

